package cn.o.generate.aspect;

import cn.o.generate.utils.R;
import cn.o.generate.utils.RRException;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 异常处理器
 *
 * @author teler
 */
@Aspect
@Component
public class ExceptionHandlerAspect {
	private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = Exception.class)
    public R resolveException(Exception ex) {
		R r;
		try {
            //记录异常日志
            logger.error(ex.getMessage(), ex);
			//类型报错
			if (ex instanceof RRException) {
			    r=R.error(ex.getMessage());
			}else if(ex instanceof DuplicateKeyException){
				r = R.error("数据库中已存在该记录");
			}else{
				r = R.error();
			}
			return r;
		} catch (Exception e) {
			logger.error("ExceptionHandler 异常处理失败", e);
			r=R.error(e.getMessage());
			return r;
		}
	}
}
